package han.study.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 数据库操作的工具类
 */
public class JDBCUtils {
    /**
     * 获取连接公共方法
     * @return Connection con
     * @throws Exception
     */
    public static Connection getConnection() throws Exception{
        InputStream in =  ClassLoader.getSystemResourceAsStream("jdbc.properties");
        Properties props = new Properties();
        props.load(in);
        String url = props.getProperty("url");
        String user = props.getProperty("user");
        String password = props.getProperty("password");
        String driverClass = props.getProperty("driverClass");
        Class.forName(driverClass);
        Connection conn = DriverManager.getConnection(url,user,password);
        return conn;
    }

    /**
     * 关闭资源公共方法
     * @param conn
     * @param ps
     */
    public static void closeResource(Connection conn, Statement ps){
        if(ps != null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.setAutoCommit(true);
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭资源重载方法
     * @param conn
     * @param ps
     * @param rs
     */
    public static void closeResource(Connection conn, PreparedStatement ps, ResultSet rs){
        if(conn != null){
            try{
                conn.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if(ps != null){
            try{
                ps.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if(rs != null){
            try{
                ps.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
